package com.ruitaowang.admin.view.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIShoppingcartController extends BaseController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private GoodsAttributeLinkService goodsAttributeLinkService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CouponService couponService;

    @RequestMapping(value = "/api/wap/shoppingCart", method = RequestMethod.GET)
    public String list(ShoppingCart shoppingCart,int page,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        //检测已下架 或者删除的商品 从购物车中移除
        ShoppingCart testShoppingCart = new ShoppingCart();
        testShoppingCart.setUserId(Long.parseLong(userId));
         List<ShoppingCart> testShoppingCartList = shoppingCartService.select(testShoppingCart);
         if (!ObjectUtils.isEmpty(testShoppingCartList)){
             for (ShoppingCart sc:testShoppingCartList){
                 Goods goods=goodsService.selectByPK(sc.getGoodsId());
                 if (goods.getRstatus() == 1 || goods.getGoodsOnline() == 0){
                     shoppingCartService.delete(sc.getCartId());
                 }
             }
         }
         //查询购物车
        shoppingCart.setPage(page);
        shoppingCart.setUserId(Long.parseLong(userId));
        List<ShoppingCart> shoppingCarts = shoppingCartService.selectForPage(shoppingCart);
        if (ObjectUtils.isEmpty(shoppingCarts)){
            return this.renderJson(MsgOut.error("清单中暂无商品"));
        }
        HashMap map = new HashMap();
        List out = new ArrayList();
        List<GoodsVO> outList=new ArrayList<>();
        for (ShoppingCart sc:shoppingCarts){
            GoodsVO goodsVO=new GoodsVO();
            Goods goods=goodsService.selectByPK(sc.getGoodsId());
            BeanUtils.copyProperties(goods, goodsVO);
            goodsVO.setGoodsNumber(sc.getGoodsNumber());
            goodsVO.setCartId(sc.getCartId());
           outList.add(goodsVO);
        }
        for (GoodsVO goodsVO:outList){
            map.put(goodsVO.getGoodsProviderId(),goodsVO);
        }
        List<Long> list = new ArrayList<>();
        map.forEach((key, value) -> {
            list.add(Long.parseLong(key.toString()));
        });
        for (Long li:list){
            List goodsList = new ArrayList();
            for (GoodsVO goodsVO:outList){
                if (li.equals(goodsVO.getGoodsProviderId())){
                    goodsList.add(goodsVO);
                }
            }
            CompanyVO companyVO = new CompanyVO();
            Company company=companyService.selectByPK(li);
            BeanUtils.copyProperties(company, companyVO);
            companyVO.setGoodsList(goodsList);

            if (!ObjectUtils.isEmpty(company.getCompanyId())) {
                Coupon coupon = new Coupon();
                coupon.setCompanyId(company.getCompanyId());
                coupon.setCouponType((byte) 0);
                List<Coupon> coupons = couponService.select(coupon);
                companyVO.setCouponList(coupons);
            } else {
                List kong = new ArrayList();
                companyVO.setCouponList(kong);
            }
            out.add(companyVO);
        }
        MsgOut o = MsgOut.success(out);
        o.setRecords(shoppingCart.getRecords());
        o.setTotal(shoppingCart.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/shoppingCart", method = RequestMethod.POST)
    public String create(ShoppingCart shoppingCart,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingCart.setUserId(Long.parseLong(userId));
        ShoppingCart shoppingCartSelect = new ShoppingCart();
        shoppingCartSelect.setUserId(Long.parseLong(userId));
        shoppingCartSelect.setGoodsId(shoppingCart.getGoodsId());

        //check exists
        List<ShoppingCart> shoppingCarts = shoppingCartService.select(shoppingCartSelect);
        if (ObjectUtils.isEmpty(shoppingCarts)) {
            shoppingCart.setGoodsNumber(1);
            shoppingCart = shoppingCartService.insert(shoppingCart);
        } else {
            shoppingCart.setGoodsNumber(shoppingCarts.get(0).getGoodsNumber() + 1);
            shoppingCart.setCartId(shoppingCarts.get(0).getCartId());
            shoppingCart = shoppingCartService.update(shoppingCart);
        }
        MsgOut o = MsgOut.success(shoppingCart);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/shoppingCart", method = RequestMethod.PUT)
    public String update(ShoppingCart shoppingCart,@RequestHeader(value="headId",required = false) String userId) {
//        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(shoppingCart)){
            return this.renderJson(MsgOut.error("no data"));
        }
        shoppingCart.setUserId(Long.parseLong(userId));
        if(Long.parseLong(userId) == shoppingCart.getUserId()){
            shoppingCartService.update(shoppingCart);
            MsgOut o = MsgOut.success(shoppingCart);
            return this.renderJson(o);
        }
        return this.renderJson(MsgOut.error("denied"));
    }

    @RequestMapping(value = "/api/wap/shoppingCart/{shoppingCartId}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("shoppingCartId") Long shoppingCartId,@RequestHeader(value="headId",required = false) String userId) {
//        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        ShoppingCart shoppingCart1 = shoppingCartService.selectByPK(shoppingCartId);
        LOGGER.error("CurrentUser : {}", JSON.toJSON(userId));
        LOGGER.error("CurrentShoppingCart : {}", JSON.toJSON(shoppingCart1));
        LOGGER.error("shoppingCart1.getUserId() : {}", shoppingCart1.getUserId());
        LOGGER.error("user.getId() : {}", userId);
        LOGGER.error(" shoppingCart1.getUserId() == user.getId() : {}", shoppingCart1.getUserId() == Long.parseLong(userId));
        if(Long.parseLong(userId) == shoppingCart1.getUserId()){
            LOGGER.error("DELETE shoppingCartId : {}", shoppingCartId);
            shoppingCartService.delete(shoppingCartId);
            return this.renderJson(MsgOut.success());
        }
        return this.renderJson(MsgOut.error("denied"));
    }
    @RequestMapping(value = "/api/wap/shoppingCart/all", method = RequestMethod.POST)
    public String deleteAll(String orderJson,@RequestHeader(value="headId",required = false) String userId) {
//        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        JSONArray objects = JSON.parseArray(orderJson);
        for (int i = 0; i < objects.size(); i++){
            CompanyVO companyVO=JSON.parseObject(objects.get(i).toString(), CompanyVO.class);
            for (GoodsVO goodsVO:companyVO.getGoodsList()){
                shoppingCartService.delete(goodsVO.getCartId());
            }
        }
            return this.renderJson(MsgOut.success(orderJson));
    }

    @RequestMapping(value = "/api/shoppingCart/{shoppingCartId}", method = RequestMethod.GET)
    public String selectByPK(@PathVariable("shoppingCartId") Long shoppingCartId) {
        ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
        ShoppingCart shoppingCart = shoppingCartService.selectByPK(shoppingCartId);
        Goods goods = goodsService.selectByPK(shoppingCart.getGoodsId());
        BeanUtils.copyProperties(goods, shoppingCartVo);
        BeanUtils.copyProperties(shoppingCart, shoppingCartVo);
        shoppingCartVo.setGoodsAttrValues(goodsAttributeLinkService.getGoodsAttributeForString(shoppingCartVo.getGoodsAttrLinkId()));
        MsgOut o = MsgOut.success(shoppingCartVo);
        return this.renderJson(o);
    }

    /**
     * 购物车个数
     * @param shoppingCart
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/shoppingCart/count", method = RequestMethod.GET)
    public String count(ShoppingCart shoppingCart,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingCart.setUserId(userId);
        MsgOut o = MsgOut.success(shoppingCartService.count(shoppingCart));
        return this.renderJson(o);
    }
}
